package com.ld.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ld.common.R;
import com.ld.entity.User;
import com.ld.web.dto.LoginParamsDto;
import com.ld.web.shiro.ShiroUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @RequestMapping(value = "ajaxLogin" , method = RequestMethod.POST)
    public R shiroLogin(@RequestBody LoginParamsDto loginParamsDto){
        try {
            Subject subject = ShiroUtils.getSubject();
            //密码加密
            //sha256加密
           String password = new Sha256Hash(loginParamsDto.getPassword()).toHex();
            UsernamePasswordToken token = new UsernamePasswordToken(loginParamsDto.getUserName(), password);
            subject.login(token);
        }catch (UnknownAccountException e) {
            return R.error(e.getMessage());
        } catch (IncorrectCredentialsException e) {
            return R.error(e.getMessage());
        } catch (LockedAccountException e) {
            return R.error(e.getMessage());
        } catch (AuthenticationException e) {
            return R.error("账户验证失败");
        }
        return R.ok();
    }

    /**
     * 未登录，shiro应重定向到登录界面，此处返回未登录状态信息由前端控制跳转页面
     * @return
     */
    @RequestMapping(value = "/unauth")
    public R unauth() {
       return R.error("未登录");
    }

    /**
     * 未登录，shiro应重定向到登录界面，此处返回未登录状态信息由前端控制跳转页面
     * @return
     */
    @RequestMapping(value = "/login")
    public R login() {
        return R.error("请登录");
    }
//
//    @RequestMapping(value = "/error")
//    public R error(){
//        return R.error("系统错误");
//    }

    @RequestMapping("getUser")
    public R gerUserInfo(){
        User user = ShiroUtils.getUserEntity();
//        User user = (User) ShiroUtils.getSubject().getSession().getAttribute("curUser");
        JSONObject jsonObject = JSON.parseObject(JSONObject.toJSONString(user));
        return R.ok();
    }
}
